<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <title>成远生产管控平台 - 后台管理系统</title>
  <script src="https://cdn.jsdelivr.net/npm/moment@2.29.4/moment.min.js"></script>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css">
  <script src="https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/file-saver@2.0.5/dist/FileSaver.min.js"></script>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/layui@2.8.14/dist/css/layui.min.css">
  <script src="https://cdn.jsdelivr.net/npm/layui@2.8.14/dist/layui.min.js"></script>

  <style>
    :root {
      --primary-color: #009688;
      --secondary-color: #2F4056;
      --accent-color: #1E9FFF;
      --light-gray: #f5f7fa;
      --dark-gray: #393D49;
      --border-radius: 8px;
      --box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    }

    body {
      margin: 0;
      padding: 0;
      min-height: 100vh;
      font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", Arial, sans-serif;
      font-size: 14px;
      color: #333;
      background-color: #f0f2f5;
      background-image: url('https://picsum.photos/id/180/1920/1080');
      background-size: cover;
      background-position: center;
      background-repeat: no-repeat;
    }

    /* 全局组件样式 */
    .layui-table th,
    .layui-form-label,
    .layui-btn {
      font-weight: 500;
    }

    .layui-table td {
      font-size: 13px;
    }

    .layui-btn {
      border-radius: var(--border-radius);
      transition: all 0.3s ease;
    }

    .layui-btn-primary:hover {
      border-color: var(--primary-color);
      color: var(--primary-color);
    }

    .layui-form-select dl dd.layui-this {
      background-color: var(--primary-color);
    }

    .layui-form-checked[lay-skin="primary"] i {
      border-color: var(--primary-color);
      background-color: var(--primary-color);
    }

    .layui-tab-title li {
      font-weight: 500;
    }

    .layui-tab-title .layui-this {
      color: var(--primary-color);
    }

    .layui-tab-title .layui-this:after {
      border-bottom: 2px solid var(--primary-color);
    }

    /* 页面结构样式 */
    .header-container {
      background-color: #ffffff;
      padding: 15px 30px;
      box-shadow: var(--box-shadow);
      display: flex;
      justify-content: space-between;
      align-items: center;
      position: sticky;
      top: 0;
      z-index: 1000;
    }

    .header-left {
      display: flex;
      align-items: center;
    }

    .header-logo {
      display: flex;
      align-items: center;
      margin-right: 20px;
      padding-right: 20px;
      border-right: 1px solid #eee;
    }

    .header-logo i {
      font-size: 24px;
      color: var(--primary-color);
      margin-right: 10px;
    }

    .header-title {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
    }

    .header-info {
      color: #666;
    }

    .header-right {
      display: flex;
      align-items: center;
    }

    .user-info {
      display: flex;
      align-items: center;
      margin-right: 20px;
    }

    .user-avatar {
      width: 32px;
      height: 32px;
      border-radius: 50%;
      background-color: var(--primary-color);
      color: white;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 10px;
    }

    .logout-btn {
      background-color: #ff5722;
      color: white;
    }

    .logout-btn:hover {
      background-color: #d84a1d;
    }

    .layui-layout-admin {
      margin: 20px;
      border-radius: var(--border-radius);
      overflow: hidden;
      box-shadow: var(--box-shadow);
      background-color: rgba(255, 255, 255, 0.95);
    }

    .layui-side {
      width: 220px !important;
      background-color: var(--secondary-color);
    }

    .layui-body {
      padding: 20px;
      overflow: auto;
    }

    /* 导航菜单样式 */
    .layui-nav-tree {
      width: 220px;
    }

    .layui-nav-tree .layui-nav-item {
      margin: 0;
    }

    .layui-nav-tree .layui-nav-item a {
      padding-left: 25px;
      height: 50px;
      line-height: 50px;
      transition: all 0.3s ease;
    }

    .layui-nav-tree .layui-nav-item a:hover {
      background-color: rgba(255, 255, 255, 0.1);
    }

    .layui-nav-tree .layui-nav-item.layui-this {
      background-color: var(--primary-color);
    }

    .layui-nav-tree .layui-nav-item.layui-this a:hover {
      background-color: var(--primary-color);
    }

    .layui-nav-tree .layui-nav-item i {
      margin-right: 10px;
    }

    .content-container {
      background-color: white;
      border-radius: var(--border-radius);
      box-shadow: var(--box-shadow);
      padding: 20px;
      margin-bottom: 20px;
    }
    .section-title {
      font-size: 20px;
      font-weight: 600;
      margin-bottom: 20px;
      color: var(--secondary-color);
      display: flex;
      align-items: center;
    }
    .section-title i {
      margin-right: 10px;
      color: var(--primary-color);
    }
    .layui-table thead tr {
      background-color: #f8f9fa;
    }
    .layui-table th {
      font-weight: 600;
      color: var(--secondary-color);
    }
    .layui-table tbody tr:hover {
      background-color: #f5f8ff;
    }
    .table-action-btn {
      height: 28px;
      line-height: 28px;
      padding: 0 8px;
      font-size: 12px;
      margin-right: 5px;
    }
    .query-form {
      display: flex;
      flex-wrap: wrap;
      gap: 15px;
      padding: 20px;
      background-color: #f8f9fa;
      border-radius: var(--border-radius);
      margin-bottom: 20px;
    }
    .query-form-item {
      display: flex;
      align-items: center;
      margin-bottom: 0;
    }
    .query-form-label {
      width: auto;
      padding-right: 10px;
      font-weight: 500;
      color: var(--secondary-color);
    }
    .query-form-input {
      width: 180px;
    }
    .query-form-checkbox {
      margin-left: 10px;
    }
    .query-form-actions {
      display: flex;
      gap: 10px;
      margin-left: auto;
    }
    .statistics-container {
      padding: 15px 20px;
      background-color: #f0f2f5;
      border-radius: var(--border-radius);
      margin-top: 20px;
      font-weight: 500;
      color: var(--secondary-color);
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .statistics-item {
      display: flex;
      align-items: center;
    }
    .statistics-item i {
      margin-right: 8px;
      color: var(--primary-color);
    }
    .statistics-value {
      font-weight: 600;
      color: #ff5722;
      margin-left: 5px;
    }
    @media screen and (max-width: 1200px) {
      .query-form {
        flex-direction: column;
        gap: 10px;
      }
      .query-form-item {
        width: 100%;
      }
      .query-form-input {
        width: 100%;
      }
      .query-form-actions {
        margin-left: 0;
        width: 100%;
      }
    }

    @media screen and (max-width: 768px) {
      .header-container {
        flex-direction: column;
        padding: 15px;
      }

      .header-left, .header-right {
        width: 100%;
        justify-content: center;
      }

      .header-logo {
        border-right: none;
        margin-right: 0;
        padding-right: 0;
        margin-bottom: 10px;
      }

      .user-info {
        margin-right: 0;
        margin-bottom: 10px;
      }

      .layui-side {
        display: none;
      }

      .layui-body {
        left: 0 !important;
      }

      .query-form-item {
        flex-direction: column;
        align-items: flex-start;
      }
      .query-form-label {
        margin-bottom: 5px;
      }
      .query-form-input,
      .layui-input-inline {
        width: 100%;
      }
    }
  </style>
</head>

<body>
<!-- 顶部导航栏 -->
<div class="header-container">
  <div class="header-left">
    <div class="header-logo">
      <i class="fa fa-cogs"></i>
      <h3 class="header-title">成远生产管控平台</h3>
    </div>
    <div class="header-info">
      <p style="margin: 0;">欢迎您，<span id="usernameDisplay"></span>！</p>
      <p style="margin: 0;">当前时间：<span id="currentTime"></span></p>
    </div>
  </div>
  <div class="header-right">
    <div class="user-info">
      <div class="user-avatar"><i class="fa fa-user"></i></div>
      <span id="usernameDisplayMobile"></span>
    </div>
    <button class="layui-btn logout-btn" id="logoutBtn">
      <i class="fa fa-sign-out"></i> 退出系统
    </button>
  </div>
</div>

<div class="layui-layout layui-layout-admin">
  <!-- 左侧导航栏 -->
  <div class="layui-side">
    <div class="layui-side-scroll">
      <ul class="layui-nav layui-nav-tree" lay-filter="adminNav">
        <!-- 用户权限管理 -->
        <li class="layui-nav-item" data-tab="user">
          <a href="javascript:;">
            <i class="fa fa-users"></i>
            <span>用户权限管理</span>
          </a>
        </li>
        <!-- 数据查询 -->
        <li class="layui-nav-item" data-tab="query">
          <a href="javascript:;">
            <i class="fa fa-search"></i>
            <span>数据查询</span>
          </a>
        </li>
      </ul>
    </div>
  </div>

  <!-- 内容区域 -->
  <div class="layui-body">
    <div class="layui-tab" lay-filter="adminTabs" lay-allowclose="false">
      <ul class="layui-tab-title">
        <li class="layui-this" lay-id="user">用户管理</li>
        <li lay-id="query">数据查询</li>
      </ul>

      <div class="layui-tab-content">
        <!-- 用户管理 -->
        <div class="layui-tab-item layui-show">
          <div class="content-container">
            <div class="section-title">
              <i class="fa fa-users"></i>
              用户管理
            </div>
            <div class="layui-btn-container">
              <button class="layui-btn layui-btn-primary" id="addUserBtn">
                <i class="fa fa-plus"></i> 添加用户
              </button>
            </div>
            <table id="userTable" lay-filter="userTable"></table>
          </div>
        </div>

        <!-- 数据查询 -->
        <div class="layui-tab-item">
          <div class="content-container">
            <div class="section-title">
              <i class="fa fa-search"></i>
              数据查询
            </div>

            <form class="layui-form query-form" lay-filter="queryForm">
              <div class="query-form-item">
                <label class="query-form-label">门岗</label>
                <div class="layui-input-inline query-form-input">
                  <select name="gate" id="gate" lay-verify="gate">
                    <option value="">请选择</option>
                    <option value="门牌1">门牌1</option>
                    <option value="门牌2">门牌2</option>
                  </select>
                </div>
                <div class="layui-form-mid query-form-checkbox">
                  <input type="checkbox" name="useGate" id="useGate"  title="使用门岗查询" data-target="gate" checked>
                </div>
              </div>

              <div class="query-form-item">
                <label class="query-form-label">车牌号</label>
                <div class="layui-input-inline query-form-input">
                  <input type="text" name="plate" id="plate" placeholder="车牌号" class="layui-input">
                </div>
                <div class="layui-form-mid query-form-checkbox">
                  <input type="checkbox" name="usePlate" id="usePlate" title="使用车牌号查询" data-target="plate" checked>
                </div>
              </div>

              <div class="query-form-item">
                <label class="query-form-label">施工单位</label>
                <div class="layui-input-inline query-form-input">
                  <select name="belonging" id="belonging" lay-verify="required">
                    <option value="">请选择</option>
                    <option value="施工单位A">施工单位A</option>
                    <option value="施工单位B">施工单位B</option>
                    <option value="施工单位C">施工单位C</option>
                  </select>
                </div>
                <div class="layui-form-mid query-form-checkbox">
                  <input type="checkbox" name="useBelonging" id="useBelonging" title="使用施工单位查询" data-target="belonging" checked>
                </div>
              </div>

              <div class="query-form-item">
                <label class="query-form-label">开始时间</label>
                <div class="layui-input-inline query-form-input">
                  <input type="text" name="startTime" id="startTime" placeholder="开始时间" class="layui-input">
                </div>
                <div class="layui-form-mid query-form-checkbox">
                  <input type="checkbox" name="useStartTime" id="useStartTime" title="使用开始时间查询" data-target="startTime" checked>
                </div>
              </div>

              <div class="query-form-item">
                <label class="query-form-label">结束时间</label>
                <div class="layui-input-inline query-form-input">
                  <input type="text" name="endTime" id="endTime" placeholder="结束时间" class="layui-input">
                </div>
                <div class="layui-form-mid query-form-checkbox">
                  <input type="checkbox" name="useEndTime" id="useEndTime" title="使用结束时间查询" data-target="endTime" checked>
                </div>
              </div>

              <div class="query-form-item query-form-actions">
                <button class="layui-btn" lay-submit lay-filter="queryForm">
                  <i class="fa fa-search"></i> 查询
                </button>
                <button class="layui-btn layui-btn-normal" id="exportBtn">
                  <i class="fa fa-download"></i> 导出Excel
                </button>
                <button class="layui-btn layui-btn-normal" id="exportBtnNew">
                  <i class="fa fa-download"></i> 导出Excel测试
                </button>
              </div>
            </form>

            <table id="dataTable" lay-filter="dataTable"></table>

            <div class="statistics-container">
              <div class="statistics-item">
                <i class="fa fa-balance-scale"></i>
                <span>总重量:</span>
                <span class="statistics-value" id="totalWeight">0.00</span>
                <span>吨</span>
              </div>
              <div class="statistics-item">
                <i class="fa fa-cubes"></i>
                <span>总体积:</span>
                <span class="statistics-value" id="totalVolume">0.00</span>
                <span>立方米</span>
              </div>
              <div class="statistics-item">
                <i class="fa fa-truckRecord"></i>
                <span>总记录:</span>
                <span class="statistics-value" id="totalCount">0</span>
                <span>条</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- 用户编辑弹窗模板 -->
<script type="text/html" id="editUserTpl">
  <form class="layui-form" lay-filter="editUserForm" style="padding:20px">
    <div class="layui-form-item">
      <label class="layui-form-label">用户名</label>
      <div class="layui-input-block">
        <input type="text" name="username"
               value="{{ d.username || '' }}"
               lay-verify="{{# if(!d.id){ }}required|username{{# }else{ }}username{{# } }}"
        class="layui-input"
        {{# if(d.id){ }} disabled {{# } }}>
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">密码</label>
      <div class="layui-input-block">
        <input type="password" name="password"
               placeholder="{{ d.id ? '留空不修改' : '必填项' }}"
               lay-verify="{{ d.id ? '' : 'required' }}|password"
               class="layui-input">
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">角色</label>
      <div class="layui-input-block">
        <select name="isAdmin" lay-verify="required">
          <option value="true" {{ d.isAdmin ==true ? 'selected' : '' }}>管理员</option>
          <option value="false" {{ d.isAdmin ==false ? 'selected' : '' }}>普通用户</option>
        </select>
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">所属单位</label>
      <div class="layui-input-block">
        <select name="unitId" lay-verify="required" lay-search>
          <!-- 动态生成选项 -->
          {{# layui.each(d.units, function(index, item) { }}
          <option value="{{ item.id }}" {{ item.id == d.unitId ? 'selected' : '' }}>{{ item.unitName }}</option>
          {{# }); }}
        </select>
      </div>
    </div>
    <input type="hidden" name="id" value="{{ parseInt(d.id)||0}}">
    <div class="layui-form-item">
      <div class="layui-input-block">
        <button class="layui-btn" lay-submit>
          <i class="fa fa-save"></i> 提交
        </button>
        <button type="reset" class="layui-btn layui-btn-primary">
          <i class="fa fa-refresh"></i> 重置
        </button>
      </div>
    </div>
  </form>
</script>

<!-- 用户添加弹窗模板 -->
<script type="text/html" id="addUserTpl">
  <form class="layui-form" id="addUserForm"  lay-filter="addUserForm" style="padding:20px">
    <div class="layui-form-item">
      <label class="layui-form-label">用户名</label>
      <div class="layui-input-block">
        <!-- 禁用自动填充 -->
        <input type="text" name="username" autocomplete="off"
               lay-verify="required|username" class="layui-input">
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">密码</label>
      <div class="layui-input-block">
        <!-- 禁用自动填充 -->
        <input type="password" name="password" autocomplete="off"
               lay-verify="required|password" class="layui-input">
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">角色</label>
      <div class="layui-input-block">
        <select name="isAdmin" lay-verify="required">
          <option value="true" {{ d.isAdmin==true ? 'selected' : '' }}>管理员</option>
          <option value="false" {{ d.isAdmin==false ? 'selected' : '' }}>普通用户</option>
        </select>
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">所属单位</label>
      <div class="layui-input-block">
        <select name="unitId" lay-verify="required" lay-search>
          <!-- 动态生成选项 -->
          {{# layui.each(d.units, function(index, item) { }}
          <option value="{{ item.id }}" {{ item.id == d.unitId ? 'selected' : '' }}>{{ item.unitName }}</option>
          {{# }); }}
        </select>
      </div>
    </div>

    <div class="layui-form-item">
      <div class="layui-input-block">
        <button class="layui-btn" lay-submit>
          <i class="fa fa-save"></i> 提交
        </button>
        <button type="reset" class="layui-btn layui-btn-primary">
          <i class="fa fa-refresh"></i> 重置
        </button>
      </div>
    </div>
  </form>
</script>

<!-- 数据编辑弹窗模板 -->
<script type="text/html" id="dataEditTpl">
  <form class="layui-form" lay-filter="dataEditForm" style="padding:20px">
    <div class="layui-form-item">
      <label class="layui-form-label">门岗</label>
      <div class="layui-input-block">
        <input type="text" name="gate" value="{{ d.gate }}" class="layui-input">
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">施工单位</label>
      <div class="layui-input-block">
        <input type="text" name="belonging" value="{{ d.belonging }}" class="layui-input">
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">车牌号</label>
      <div class="layui-input-block">
        <input type="text" name="plate" value="{{ d.plate }}" class="layui-input" lay-verify="plate">
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">时间</label>
      <div class="layui-input-block">
        <input type="text" name="time" value="{{ d.time }}" class="layui-input" lay-verify="required">
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">材料</label>
      <div class="layui-input-block">
        <input type="text" name="material" value="{{ d.material }}" class="layui-input">
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">密度</label>
      <div class="layui-input-block">
        <input type="number" name="density" value="{{ d.density }}" step="0.01" class="layui-input">
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">体积(m³)</label>
      <div class="layui-input-block">
        <input type="number" name="volume" value="{{ d.volume }}" step="0.01" class="layui-input">
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">重量(吨)</label>
      <div class="layui-input-block">
        <input type="number" name="weight" value="{{ d.weight }}" step="0.01" class="layui-input">
      </div>
    </div>
    <input type="hidden" name="id" value="{{ d.id }}">
    <div class="layui-form-item">
      <div class="layui-input-block">
        <button class="layui-btn" lay-submit>
          <i class="fa fa-save"></i> 保存
        </button>
        <button type="button" class="layui-btn layui-btn-primary" onclick="resetForm()">
          <i class="fa fa-refresh"></i> 重置
        </button>
      </div>
    </div>
  </form>
</script>
<!-- 用户管理操作列模板 -->
<script type="text/html" id="userBar">
  <div class="layui-btn-group">
    <button class="layui-btn layui-btn-xs table-action-btn" lay-event="edit">
      <i class="fa fa-edit"></i> 编辑
    </button>
    <button class="layui-btn layui-btn-xs layui-btn-danger table-action-btn" lay-event="delete">
      <i class="fa fa-trash"></i> 删除
    </button>
  </div>
</script>

<!-- 数据查询操作列模板 -->
<script type="text/html" id="barDemo">
  <div class="layui-btn-group">
    <button class="layui-btn layui-btn-xs table-action-btn" lay-event="edit">
      <i class="fa fa-edit"></i> 编辑
    </button>
    <button class="layui-btn layui-btn-xs layui-btn-danger table-action-btn" lay-event="delete">
      <i class="fa fa-trash"></i> 删除
    </button>
  </div>
</script>

<script>
  let currentQueryParams = {}; // ← 新增：保存当前查询参数
  let currentTableData = []; // ← 新增：保存当前表格数据
  layui.use(['element', 'table', 'form', 'layer', 'laydate'], function() {
    const $ = layui.$,
            element = layui.element,
            table = layui.table,
            form = layui.form,
            layer = layui.layer,
            laydate = layui.laydate;

    // 初始化日期选择器
    laydate.render({ elem: '#startTime', type: 'datetime' });
    laydate.render({ elem: '#endTime', type: 'datetime' });

    // 用户管理表格
    const userTable = table.render({
      elem: '#userTable',
      url: 'http://localhost:8080/user/users',
      cols: [[
        {field: 'id', title: 'ID', width: 80},
        {field: 'username', title: '用户名', width: 150},
        {
          field: 'password',
          title: '密码',
          width: 120,
          templet: () => '******' // 显示为密文
        },
        {field: 'isAdmin', title: '角色', width: 120, templet: d => d.isAdmin ?
                  '<span class="layui-badge layui-bg-blue">管理员</span>' :
                  '<span class="layui-badge layui-bg-gray">普通用户</span>'
        },
        {field: 'unitId', title: '所属单位', width: 180, templet: d => unitMap[d.unitId] || '未知单位'},
        {
          field: 'registerTime',
          title: '注册时间',
          width: 160,
          templet: d => moment(d.registerTime).format('YYYY-MM-DD HH:mm:ss')
        },
        {title: '操作', width: 200, toolbar: '#userBar'}
      ]],
      page: true,
      limit: 10,
      response: {statusCode: 0},
      request: {
        pageName: 'page',   // 默认就是 page
        limitName: 'size'   // 如果后端接收的是 size，必须显式声明
      },
      done: function() {
        // 表格加载完成后的回调
      }
    });

    // 数据查询表格
    const dataTable = table.render({
      elem: '#dataTable',
      url: 'http://localhost:8080/truckRecord/truckRecords',
      request: {
        pageName: 'page',   // 对应后端接收的页码参数名
        limitName: 'size'   // 对应后端接收的每页条数参数名
      },
      cols: [[
        {field: 'id', title: '序号', width: 60},
        {field: 'uuid', title: '唯一标识', width: 60},
        {field: 'gate', title: '门岗', width: 80},
        {field: 'belonging', title: '施工单位', width: 90},
        {field: 'plate', title: '车牌号', width: 90},
        {field: 'time', title: '时间', width: 80},
        {field: 'material', title: '材料', width: 60},
        {field: 'density', title: '密度', width: 60, templet: d => (d.density || 0).toFixed(2)},
        {field: 'volume', title: '体积(m³)', width: 80, templet: d => (d.volume || 0).toFixed(2)},
        {field: 'weight', title: '重量(吨)', width: 80, templet: d => (d.weight || 0).toFixed(2)},
        {field: 'scan', title: '扫描状态', width: 60, templet: d => d.scan ?
                  '<span class="layui-badge layui-bg-green">已扫描</span>' :
                  '<span class="layui-badge layui-bg-orange">未扫描</span>'
        },
        {field: 'status', title: '同步状态', width: 60, templet: d => d.status ?
                  '<span class="layui-badge layui-bg-green">已同步</span>' :
                  '<span class="layui-badge layui-bg-orange">未同步</span>'
        },
        {title: '操作', width: 180, toolbar: '#barDemo'}
      ]],
      page: true,
      limit: 10,
      limits:  [10, 20, 30, 40, 50],
      response: {
        statusCode: 0,     // 成功的状态码
        countName: 'count', // 后端返回的总记录数字段
        dataName: 'data'    // 后端返回的数据字段
      },
      done: function(res) {
        updateStatistics(res);
        currentTableData = res.data; // ← 保存当前表格数据用于导出
      }
    });

    // 更新统计信息
    function updateStatistics(data) {
      const totalWeight = data.totalWeight || 0;
      const totalVolume = data.totalVolume || 0;
      const totalCount = data.count || 0;

      $('#totalWeight').text(totalWeight.toFixed(2));
      $('#totalVolume').text(totalVolume.toFixed(2));
      $('#totalCount').text(totalCount);
    }

    // 初始化导航状态
    function initNav() {
      $('.layui-nav-item[data-tab="user"]')
              .addClass('layui-this')
              .siblings().removeClass('layui-this');
      element.render('nav');
    }

    // 更新当前时间
    function updateCurrentTime() {
      const now = moment().format('YYYY年MM月DD日 HH:mm:ss');
      $('#currentTime').text(now);
      $('#currentTimeMobile').text(now);
    }

    setInterval(updateCurrentTime, 1000);
    updateCurrentTime(); // 初始化一次

    // 添加全局单位映射
    let unitMap = {};

    // 初始化单位数据
    async function initUnits() {
      try {
        const res = await $.ajax({
          url: 'http://localhost:8080/user/units',
          method: 'GET'
        });
        res.data.forEach(item => {
          unitMap[item.id] = item.unitName;
        });
      } catch (error) {
        console.error('单位数据加载失败:', error);
        layer.msg('单位数据加载失败', {icon: 2});
      }
    }

    // 自动绑定 checkbox 控制目标输入项的禁用状态
    $(document).on('change', 'input[type="checkbox"][data-target]', function () {
      const target = $('#' + $(this).data('target'));
      if (this.checked) {
        target.removeAttr('disabled');
        } else {
        target.attr('disabled', 'disabled').val('');
      }
    }).trigger('change'); // 初始化一次状态

    // 页面加载完成后执行
    $(document).ready(async function() {
      await initUnits();  // 先加载单位数据
      const username = sessionStorage.getItem('username');
      const unitId = sessionStorage.getItem('unitId');

      if (!username || !unitId) {
        layer.msg('请先登录', {icon: 2});
        setTimeout(() => window.location.href = '/login.html', 1500);
      } else {
        $('#usernameDisplay').text(username);
        $('#usernameDisplayMobile').text(username);
        initNav();
        element.init();
      }
    });

    // 导航栏切换事件
    $(document).on('click', '.layui-nav-item', function () {
      const $navItem = $(this);
      const tabId = $navItem.data('tab');
      if (!tabId) return;

      // 更新导航状态
      $navItem.addClass('layui-this').siblings().removeClass('layui-this');

      // 切换标签页
      setTimeout(() => {
        element.render('nav');
        element.tabChange('adminTabs', tabId);
      }, 100);
    });

    // 监听窗口变化重新渲染
    $(window).on('resize', function(){
      element.render('tab');
      element.render('nav');
    });

    // 在用户输入时实时检查用户名
    $('#usernameInput').on('blur', function() {
      if (!this.value) return;

      $.get('http://localhost:8080/user/check?username=' + this.value, function(res) {
        if(res.exists) {
          layer.tips('用户名已存在', '#usernameInput', {tips: 1});
        }
      }).fail(function(xhr) {
        console.error('检查用户名失败:', xhr);
      });
    });

    // 用户管理操作
    table.on('tool(userTable)', function(obj) {
      const data = obj.data;
      if(obj.event === 'edit') {
        console.log('编辑用户数据:', data);
        editUser(data);
      } else if(obj.event === 'delete') {
        layer.confirm('确定删除该用户？', {
          icon: 3,
          title: '确认删除'
        }, function(index) {
          $.ajax({
            url: `http://localhost:8080/user/delete/${data.id}`,
            type: 'DELETE',
            success: () => {
              layer.msg('删除成功', {icon: 1});
              userTable.reload();
            },
            error: xhr => {
              console.error('删除用户失败:', xhr);
              layer.msg('删除失败: ' + (xhr.responseJSON?.message || xhr.statusText), {icon: 2});
            }
          });
          layer.close(index);
        });
      }
    });

    // 数据编辑操作
    table.on('tool(dataTable)', function(obj) {
      const data = obj.data;
      if(obj.event === 'edit') {
        layer.open({
          type: 1,
          title: '编辑数据',
          area: ['600px', '80%'],
          content: layui.laytpl($('#dataEditTpl').html()).render(data),
          success: function(layero) {
            form.render();
          }
        });
      } else if (obj.event === 'delete') {
        layer.confirm('确定删除该记录？', {
          icon: 3,
          title: '确认删除'
        }, function(index) {
          $.ajax({
            url: `http://localhost:8080/truckRecord/delete/${data.id}`,
            type: 'DELETE',
            success: () => {
              layer.msg('删除成功', {icon: 1});
              dataTable.reload(); // 刷新表格
            },
            error: xhr => {
              console.error('删除记录失败:', xhr);
              layer.msg('删除失败: ' + (xhr.responseJSON?.message || xhr.statusText), {icon: 2});
            }
          });
          layer.close(index);
        });
      }
    });

    // 添加用户功能
    $('#addUserBtn').click(() => addUser());

    // 用户添加/编辑通用处理函数
    async function handleUserDialog(data, isEdit) {
      try {
        const loadingIndex = layer.load(1, { shade: [0.3, '#000'] });
        const units = await loadUnits();

        const title = isEdit ? '编辑用户' : '添加用户';
        const templateId = isEdit ? '#editUserTpl' : '#addUserTpl';
        const formFilter = isEdit ? 'editUserForm' : 'addUserForm';

        layer.open({
          type: 1,
          title: title,
          area: ['500px', '400px'],
          content: layui.laytpl($(templateId).html()).render({
            d: { ...data }, // 正确传递数据到模板
            units: units
          }),
          success: function(layero) {
            // 初始化表单数据
            form.val(formFilter, {
              username: data.username || '', // ← 确保使用 originalData
              password: '',
              unitId: data.unitId ? String(data.unitId) : '', // ← 确保使用 originalData
              id: String(data.id || ''),
              isAdmin: String(data.isAdmin === undefined ? false : data.isAdmin)
            });
            form.render();

            // 表单提交处理
            form.on('submit(' + formFilter + ')', function(formData) {
              handleUserSubmit(formData, isEdit,data);
              return false;
            });
          },
          end: function() {
            layer.close(loadingIndex);
          }
        });
      } catch (error) {
        console.error('初始化用户窗口失败:', error);
        layer.closeAll();
        layer.msg('初始化窗口失败', { icon: 2 });
      }
    }

    // 添加用户
    function addUser() {
      handleUserDialog({}, false);
    }

    // 编辑用户
    function editUser(data) {
      handleUserDialog(data, true);
    }

    // 处理用户提交
    function handleUserSubmit(formData, isEdit,originalData) {

      console.log('提交数据:', formData.field);
      const fields = formData.field;
      // 编辑模式强制添加用户名
      if (isEdit) {
        fields.username = originalData.username; // 从原始数据获取
      }

      // 校验逻辑
      if (isEdit) {
        // 编辑模式跳过用户名长度校验
        if (!/^[\w\u4e00-\u9fa5]{2,20}$/.test(fields.username)) {
          layer.msg('用户名格式不正确', { icon: 2 });
          return false;
        }
      } else {
        // 新增模式保持原有校验
        if (!fields.username || fields.username.trim().length < 2) {
          layer.msg('用户名至少需要2个字符', { icon: 2 });
          return false;
        }
      }

      // 校验密码（新增时必须填写）
      if (!isEdit && (!fields.password || fields.password.trim().length < 6)) {
        layer.msg('密码至少需要6个字符', { icon: 2 });
        return false;
      }

      // 校验所属单位（新增和编辑都适用）
      const rawUnitId = fields.unitId; // 原始单位ID（可能是空字符串/非法字符串）
      const unitId = parseInt(rawUnitId);
      console.log('unitId:', rawUnitId, unitId); // 添加调试信息
      if (!rawUnitId || isNaN(unitId)) {
        layer.msg('请选择有效的所属单位', { icon: 2 });
        return false;
      }

      const postData = {
        ...fields,
        isAdmin: fields.isAdmin === 'true',
        // 保留原始数据中的关键字段
        ...(isEdit && {
          id: originalData.id,
          username: originalData.username,
          unitId: originalData.unitId
        })
      };

      // 移除已禁用的字段验证
      if (isEdit) {
        delete formData.field.username; // 防止重复验证
      }
      // 处理密码（编辑时留空则不修改）
      if (isEdit && !postData.password.trim()) {
        delete postData.password; // 不发送密码字段
      }

      console.log('提交用户数据:', postData);
      // 在提交时增加数据校验日志
      console.log('提交数据:', {
        isEdit,
        originalData,
        formData: formData.field,
        postData
      });
      // 发送请求
      $.ajax({
        url: isEdit ? 'http://59.110.144.74:8080/user/update' : 'http://59.110.144.74:8080/user/add',
        method: isEdit ? 'PUT' : 'POST',
        contentType: 'application/json',
        data: JSON.stringify(postData),
        success: () => {
          layer.msg(isEdit ? '更新成功' : '添加成功');
          userTable.reload();
          layer.closeAll();
        },
        error: xhr => {
          console.error('用户操作失败:', xhr);
          const errorMsg = xhr.responseJSON?.message || '操作失败';
          layer.msg(errorMsg, {icon: 2});
        }
      });

      return false;
    }

    // 修改 loadUnits 方法为异步模式
    async function loadUnits() {
      try {
        const res = await $.ajax({
          url: 'http://localhost:8080/user/units',
          method: 'GET'
        });
        console.log('单位数据:', res.data);
        return res.data || [];
      } catch (error) {
        console.error('单位数据加载失败:', error);
        layer.msg('单位数据加载失败', {icon: 2});
        return [];
      }
    }

    // 数据编辑表单提交
    form.on('submit(dataEditForm)', function(data) {
      const fields = data.field;

      // 数据验证
      if (!fields.gate) {
        layer.msg('门岗不能为空', {icon: 2});
        return false;
      }

      if (!fields.plate) {
        layer.msg('车牌号不能为空', {icon: 2});
        return false;
      }

      if (!fields.time) {
        layer.msg('时间不能为空', {icon: 2});
        return false;
      }

      // 转换数值类型
      fields.density = parseFloat(fields.density) || 0;
      fields.volume = parseFloat(fields.volume) || 0;
      fields.weight = parseFloat(fields.weight) || 0;

      console.log('提交编辑数据:', fields);

      $.ajax({
        url: 'http://localhost:8080/truckRecord/update',
        method: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(fields),
        success: () => {
          layer.msg('更新成功');
          dataTable.reload();
          layer.closeAll();
        },
        error: xhr => {
          console.error('更新数据失败:', xhr);
          const errorMsg = xhr.responseJSON?.message || '更新失败';
          layer.msg(errorMsg, {icon: 2});
        }
      });

      return false;
    });

    // 查询表单提交
    form.on('submit(queryForm)', function(data) {
      const formData = data.field;
      const queryData = {};

      // 构建查询参数，只包含勾选的条件
      if (formData.useGate === 'on') queryData.gate = formData.gate;
      if (formData.usePlate === 'on') queryData.plate = formData.plate;
      if (formData.useBelonging === 'on') queryData.belonging = formData.belonging;
      if (formData.useStartTime === 'on') queryData.startTime = formData.startTime;
      if (formData.useEndTime === 'on') queryData.endTime = formData.endTime;

      console.log('查询参数:', queryData);

      // 更新全局变量
      currentQueryParams = queryData;

      // 重载表格，传入查询参数
      dataTable.reload({
        where: queryData,
        page: { curr: 1 } // 重新从第 1 页开始
      });

      return false;
    });


    // 导出 Excel
    $('#exportBtn').click(function() {
      layer.confirm('确定要导出当前查询结果吗？', {
        icon: 3,
        title: '确认导出'
      }, function(index) {
        layer.close(index);
        const loadingIndex = layer.load(1, { shade: [0.5, '#000'] });

        // 确保 currentQueryParams 是全局变量
        console.log('导出前的 currentQueryParams:', currentQueryParams); // ← 添加调试输出
        // 使用全局变量
        const queryParams = JSON.stringify(currentQueryParams);

        console.log('导出参数:', queryParams);

        // 请求导出接口
        $.ajax({
          url: 'http://localhost:8080/truckRecord/exportWithConditions',
          method: 'GET',
          data: queryParams,
          xhrFields: {
            responseType: 'blob' // 告诉 jQuery 这个请求的返回类型是二进制数据
          },
          success: function(blob) {
            // 创建一个 URL 对象指向这个二进制数据
            const url = URL.createObjectURL(blob);

            // 创建一个 <a> 元素用于下载
            const a = document.createElement('a');
            a.href = url;
            a.download = `车辆数据_${moment().format('YYYYMMDDHHmmss')}.xlsx`;
            document.body.appendChild(a);
            a.click();

            // 清理工作
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
            layer.close(loadingIndex);
            layer.msg('导出成功', { icon: 1 });
          },
          error: function(xhr) {
            console.error('导出失败:', xhr);
            layer.close(loadingIndex);
            layer.msg('导出失败', { icon: 2 });
          }
        });
      });
    });
    // 修改后的导出测试按钮逻辑
    $('#exportBtnNew').click(async function () {
      const loadingIndex = layer.load(1, { shade: [0.5, '#000'] });

      try {
        // 调用后端接口获取全部数据（带查询条件）
        const res = await $.ajax({
          url: 'http://localhost:8080/truckRecord/exportWithConditions',
          method: 'GET',
          data: currentQueryParams,
          dataType: 'json'
        });

        layer.close(loadingIndex);

        if (!res.data || res.data.length === 0) {
          layer.msg('没有可导出的数据', { icon: 2 });
          return;
        }

        // 转换数据格式
        const transformedData = res.data.map(item => ({
          序号: item.id,
          唯一标识: item.uuid,
          门岗: item.gate,
          施工单位: item.belonging,
          车牌号: item.plate,
          时间: moment(item.time).format('YYYY-MM-DD HH:mm:ss'),
          材料: item.material,
          密度: item.density?.toFixed(2) || '0.00',
          体积: item.volume?.toFixed(2) || '0.00',
          重量: item.weight?.toFixed(2) || '0.00',
          扫描状态: item.scan ? '已扫描' : '未扫描',
          同步状态: item.status ? '已同步' : '未同步'
        }));

        // 文件名弹窗
        layer.prompt({
          title: '请输入文件名（无需扩展名）',
          value: `矿车数据_${moment().format('YYYYMMDD')}`,
          maxlength: 50
        }, function(value, index) {
          layer.close(index);

          if (!/^[^\\/:*?"<>|]+$/.test(value)) {
            layer.msg('文件名包含非法字符', { icon: 2 });
            return;
          }

          // 生成Excel
          const worksheet = XLSX.utils.json_to_sheet(transformedData);
          const workbook = XLSX.utils.book_new();
          XLSX.utils.sheet_add_aoa(worksheet, [['序号', '唯一标识', '门岗', '施工单位', '车牌号', '时间', '材料', '密度', '体积(m³)', '重量(吨)', '扫描状态', '同步状态']], { origin: 'A1' });
          XLSX.utils.book_append_sheet(workbook, worksheet, "矿车记录");

          const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
          const blob = new Blob([excelBuffer], { type: 'application/octet-stream' });
          saveAs(blob, `${value}.xlsx`);

          layer.msg('导出成功', { icon: 1 });
        });

      } catch (error) {
        layer.close(loadingIndex);
        console.error('导出失败:', error);
        layer.msg('导出失败: ' + (error.responseJSON?.message || '服务器错误'), { icon: 2 });
      }
    });


    // 登出功能
    $('#logoutBtn').click(function() {
      layer.confirm('确定要退出系统吗？', {
        icon: 3,
        title: '确认退出'
      }, function(index) {
        // 清除会话信息
        sessionStorage.removeItem('username');
        sessionStorage.removeItem('unitId');

        // 跳转到登录页面
        window.location.href = '/login.html';
        layer.close(index);
      });
    });

    // 自定义表单验证
    form.verify({
      username: function(value,item) {
        // 跳过被禁用的字段验证
        if(item.disabled) return;

        if (value.length < 2) {
          return '用户名至少需要2个字符';
        }
        if (/[^\w\u4e00-\u9fa5]/.test(value)) {
          return '用户名只能包含字母、数字、下划线和中文';
        }
      },
      password: function(value) {
        if (value.length < 6) {
          return '密码至少需要6个字符';
        }
        if (!/[A-Za-z]/.test(value) || !/[0-9]/.test(value)) {
          return '密码需要同时包含字母和数字';
        }
      },
      plate: function(value) {
        if (value && !/^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼]{1}[A-HJ-NP-Z]{1}[A-HJ-NP-Z0-9]{4,5}[A-HJ-NP-Z0-9挂学警港澳]{0,1}$/.test(value)) {
          return '请输入正确的车牌号格式';
        }
      }
    });

    // 重置表单
    window.resetForm = function() {
      form.val('dataEditForm', {
        gate: '',
        belonging: '',
        plate: '',
        time: '',
        material: '',
        density: '',
        volume: '',
        weight: ''
      });
    };
  });
</script>
</body>
</html>